package com.simdo.g768.Dialog;

import static com.simdo.g768.MainActivity.device;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.g768.Bean.JsonObject;
import com.g768.Bean.LteBand;
import com.g768.Bean.NrBand;
import com.g768.MessageControl.MessageController;
import com.simdo.g768.Adapter.FreqResultListAdapter;
import com.simdo.g768.Bean.ArfcnPciBean;
import com.simdo.g768.Bean.CheckBoxBean;
import com.simdo.g768.Bean.ScanArfcnBean;
import com.simdo.g768.Listener.ListItemListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.FreqUtil;
import com.simdo.g768.ZApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class AutoFreqDialog extends Dialog {

    public AutoFreqDialog(Context context, int type) {
        super(context, R.style.style_dialog);
        this.mContext = context;
        this.type = type;
        View view = View.inflate(context, R.layout.dialog_freq, null);
        this.setContentView(view);
        this.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        this.setCancelable(false);   // 返回键不消失
        //设置dialog大小，这里是一个小赠送，模块好的控件大小设置
        Window window = this.getWindow();
        //window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        window.setNavigationBarColor(Color.parseColor("#2A72FF"));
        //StatusBarUtil.setLightStatusBar(window, true);
        WindowManager.LayoutParams lp = window.getAttributes();

        lp.width = mContext.getResources().getDisplayMetrics().widthPixels * 9 / 10;// 设置宽度屏幕的 9 / 10
        lp.height = mContext.getResources().getDisplayMetrics().heightPixels * 3 / 4;
        window.setAttributes(lp);
        initData();
        initView(view);
        isStopScan = false;
        tv_freq_info.setText("扫频中..");
        freqScan(); //直接开始扫频
    }

    private boolean userCancel = false;

    public boolean isUserCancel() {
        return userCancel;
    }

    public HashMap<Integer, LinkedList<ArfcnPciBean>> getResultMap() {
        HashMap<Integer, LinkedList<ArfcnPciBean>> map = new HashMap<>();
        map.put(0, TD1);
        map.put(1, TD2);
        map.put(2, TD3);
        map.put(3, TD4);
        map.put(4, TD5);
        map.put(5, TD6);
        return map;
    }
    
    private final Context mContext;
    private final int type;

    private void initData() {
        index = 0;
        scanCount = MainActivity.getInstance().scanCount;
        this.freqMap = new LinkedHashMap<>();
        this.freqList = new LinkedList<>();
        if (type == 7){
            initFreqMapOther();
        }else if (type == 0 || type == 5) {
            initFreqMapMS();
            this.freqList.addAll(MainActivity.getInstance().freqMSList);
        }else if (type == 1 || type == 6){
            initFreqMapUT();
            this.freqList.addAll(MainActivity.getInstance().freqUTList);
        }else {
            initFreqMapAll();
            this.freqList.addAll(MainActivity.getInstance().freqMSList);
            this.freqList.addAll(MainActivity.getInstance().freqUTList);
        }
    }

    private void initFreqMapOther() {
        LinkedHashMap<String, ArrayList<Integer>> freqMapAll = FreqUtil.build().getFreqMapAll();
        for (List<String> list : MainActivity.getInstance().cellMap.values()) {
            for (String bandStr : list) {
                ArrayList<Integer> arrayList = freqMapAll.get(bandStr);
                if (arrayList != null) freqMap.put(bandStr, arrayList);
            }
        }
    }

    private void initFreqMapMS() {
        freqMap = FreqUtil.build().getFreqMapMS();
    }

    private void initFreqMapUT() {
        freqMap = FreqUtil.build().getFreqMapUT();
    }

    private void initFreqMapAll(){
        freqMap = FreqUtil.build().getFreqMapAll();
    }

    TextView tv_freq_info, tv_freq_count;
    LinkedList<ScanArfcnBean> freqList;
    boolean isStopScan;
    LinkedHashMap<String, ArrayList<Integer>> freqMap;
    FreqResultListAdapter adapter;
    LinkedList<ArfcnPciBean> TD1, TD2, TD3, TD4, TD5, TD6;

    private void initView(View view) {
        tv_freq_info = view.findViewById(R.id.tv_freq_info);
        tv_freq_count = view.findViewById(R.id.tv_freq_count);

        RecyclerView freq_list = view.findViewById(R.id.freq_list);
        freq_list.setLayoutManager(new LinearLayoutManager(mContext));

        adapter = new FreqResultListAdapter(mContext, freqList, new ListItemListener() {
            @Override
            public void onItemClickListener(int position) {

            }
        });
        freq_list.setLayoutManager(new LinearLayoutManager(mContext));
        freq_list.setAdapter(adapter);

        TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        btn_cancel.setText(R.string.cancel);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btn_cancel.getText().equals(mContext.getString(R.string.cancel))) {
                    isStopScan = true;
                    userCancel = true;
                    btn_cancel.setText(mContext.getString(R.string.stoping));
                    MainActivity.getInstance().showToast(mContext.getString(R.string.freq_ending));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dismiss();
                        }
                    }, 6000);
                }
            }
        });
    }

    private boolean listIsContains(LinkedList<ArfcnPciBean> td, int arfcn) {
        // 判断列表中是否包含该频点
        for (ArfcnPciBean bean : td) {
            if (bean.getArfcn() == arfcn) return true;
        }
        return false;
    }

    boolean isScan = true;
    private void freqScan(){
        if (isScan){
            isScan = false;
            List<Integer> list = new ArrayList<>();
            for (ArrayList<Integer> arrayList : freqMap.values()) {
                list.addAll(arrayList);
            }
            startFreqScan(list);
        }else if (scanCount > 1){
            scanCount--;
            freqMap.remove("N1");
            freqMap.remove("N28");
            freqMap.remove("N79");
            freqMap.remove("B5");
            freqMap.remove("B8");
            freqMap.remove("B34");
            freqMap.remove("B38");

            isScan = true;
            freqScan();
        }else {
            MainActivity.getInstance().showToast(mContext.getString(R.string.freq_end_tip));
            //freqList.add(new ScanArfcnBean("", "", "", 1650, 3, 414, -92, 0, 0, 0, 0));

            LinkedList<LinkedList<ArfcnPciBean>> linkedLists = FreqUtil.build().decFreqList(freqList);

            TD1 = new LinkedList<>(linkedLists.get(0));
            TD2 = new LinkedList<>(linkedLists.get(1));
            TD3 = new LinkedList<>(linkedLists.get(2));
            TD4 = new LinkedList<>(linkedLists.get(3));
            TD5 = new LinkedList<>(linkedLists.get(4));
            TD6 = new LinkedList<>(linkedLists.get(5));

            LinkedList<LinkedList<ArfcnPciBean>> result = new LinkedList<>();
            result.add(TD1);
            result.add(TD2);
            result.add(TD3);
            result.add(TD4);
            result.add(TD5);
            result.add(TD6);

            if (type == 0 || type == 5){ // 移广
                for (Map.Entry<Integer, List<String>> entry : MainActivity.getInstance().cellMap.entrySet()) {
                    if (entry.getValue().contains("N41")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(504990, 50));
                            break;
                        }
                    }else if (entry.getValue().contains("B40")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(38950, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(39148, 60));
                            break;
                        }
                    }
                }
            }else if (type == 1 || type == 6){ // 联电
                for (Map.Entry<Integer, List<String>> entry : MainActivity.getInstance().cellMap.entrySet()) {
                    if (entry.getValue().contains("N78")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(627264, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(633984, 60));
                        }
                    }else if (entry.getValue().contains("B3")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(1650, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(1850, 60));
                        }
                    }else if (entry.getValue().contains("B1")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(100, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(300, 60));
                        }
                    }
                }
            }else { // 移广联电
                for (Map.Entry<Integer, List<String>> entry : MainActivity.getInstance().cellMap.entrySet()) {
                    if (entry.getValue().contains("N78")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(627264, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(633984, 60));
                        }
                    }else if (entry.getValue().contains("B3")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(1650, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(1850, 60));
                        }
                    }else if (entry.getValue().contains("B1")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(100, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(300, 60));
                        }
                    }else if (entry.getValue().contains("N41")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(504990, 50));
                        }
                    }else if (entry.getValue().contains("B40")){
                        if (result.get(entry.getKey()).isEmpty()) {
                            result.get(entry.getKey()).add(new ArfcnPciBean(38950, 50));
                            result.get(entry.getKey()).add(new ArfcnPciBean(39148, 60));
                        }
                    }
                }
            }

            StringBuilder freqStr = getStringBuilder();
            AppLog.D(freqStr.toString());

            userCancel = false;
            MainActivity.getInstance().freqList.clear();
            MainActivity.getInstance().freqList.addAll(freqList);
            if (type == 0 || type == 5) {
                MainActivity.getInstance().freqMSList.clear();
                MainActivity.getInstance().freqMSList.addAll(freqList);
            } else if (type == 1 || type == 6){
                MainActivity.getInstance().freqUTList.clear();
                MainActivity.getInstance().freqUTList.addAll(freqList);
            }
            if (this.isShowing()) dismiss();
            else MainActivity.getInstance().autoFreqEnd();
        }
    }

    private void startFreqScan(List<Integer> list){
        String id = device.getId();
        AppLog.D("AutoFreqDialog startFreqScan id = " + id + ", list size = " + list.size());
        MessageController.build().startFreqScanByArfcn(id, 0, list);
    }

    int index;
    int scanCount;

    private @NonNull StringBuilder getStringBuilder() {
        StringBuilder freqStr = new StringBuilder();
        freqStr.append("freqStr = ");
        for (ScanArfcnBean bean : freqList) {
            freqStr.append("arfcn = ").append(bean.getDl_arfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD1 = ");
        for (ArfcnPciBean bean : TD1) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD2 = ");
        for (ArfcnPciBean bean : TD2) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD3 = ");
        for (ArfcnPciBean bean : TD3) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD4 = ");
        for (ArfcnPciBean bean : TD4) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD5 = ");
        for (ArfcnPciBean bean : TD5) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }

        freqStr.append("\nTD6 = ");
        for (ArfcnPciBean bean : TD6) {
            freqStr.append("arfcn = ").append(bean.getArfcn()).append(", rsrp = ").append(bean.getRsrp()).append("   ");
        }
        return freqStr;
    }

    private void startFreqScan(String id, String band, List<Integer> list) {
        AppLog.D("FreqDialog startFreqScan id = " + id + ", band = " + band);
        tv_freq_info.setText(MessageFormat.format("{0}扫频中..", band));
        tv_freq_count.setText(MessageFormat.format("{0}/{1}", index + 1, freqMap.size()));
        MessageController.build().startFreqScanByArfcn(id, 0, list);
    }

    public void onFreqScanRsp(String id, JsonObject rsp) {
        if (rsp != null) {
            if (!isStopScan) {
                if (rsp.getInt("type") == 1) {
                    index++;
                    freqScan();
                }
            }
            if (rsp.getInt("type") == 0) {
                JSONArray jsonArray = rsp.getJSONArray("data");
                try {
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < jsonArray.length(); j++) {
                        JSONObject object = jsonArray.getJSONObject(j);
                        int band = object.getInt("band");
                        int arfcn = object.getInt("arfcn");
                        int pci = object.getInt("pci");
                        int pa = object.getInt("offsetPointA");
                        int pk = object.getInt("kssb");
                        int rsrp = object.getInt("rsrp");
                        int priority = object.getInt("priority");
                        String tac = object.getString("tac");
                        String eci = object.getString("eci");
                        JSONArray plmn = object.getJSONArray("plmn");
                        int bandwidth = object.getInt("bandwidth");

                        sb.append("arfcn = ").append(arfcn).append(", pci = ").append(pci).append(", rsrp = ").append(rsrp).append("  ");

						if (freqList.isEmpty()) {
							freqList.add(new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth));
						} else {
							boolean isAdd = true;
							for (int i = 0; i < freqList.size(); i++) {
								if (freqList.get(i).getDl_arfcn() == arfcn && freqList.get(i).getPci() == pci) {
									isAdd = false;
									freqList.remove(freqList.get(i));
									ScanArfcnBean arfcnBean = new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth);
									if (tac.isEmpty() || eci.isEmpty()) freqList.add(arfcnBean);
                                    else freqList.add(0, arfcnBean);
									break;
								}
							}
							if (isAdd) {
								ScanArfcnBean arfcnBean = new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth);
                                if (tac.isEmpty() || eci.isEmpty()) freqList.add(arfcnBean);
                                else freqList.add(0, arfcnBean);
							}
						}
						adapter.notifyDataSetChanged();
                    }
                    AppLog.I("onFreqScanRsp() isStopScan " + isStopScan + ", result = " + sb);
                } catch (JSONException e) {
                    AppLog.E("onFreqScanRsp err = " + e.getMessage());
                }
            }
        }
    }
}
